//index.js
//获取应用实例

const app = getApp();
const net = require('../../utils/request.js');
var WxParse = require('../../components/wxParse/wxParse.js');
var gio = require("../../utils/gio-minp.js").default;
// userInfo
//{ "username": "m-15021794401", "password": "e10adc3949ba59abbe56e057f20f883e", "api_request_way": 1, "regip": "127.0.0.1", "channel": 4, "user_token": "9dc0c978b067a5369f6c968b047e3930", "user_id": "657902", "is_new": 0 }, "msg": "登录成功", "state": "1"}

Page({
  data: {
    nickName: '未登录', //昵称
    dayClass: 'mideelContainer-container',
    avatarUrl: '../../image/touxiang@2x.png', //头像
    showType: 1, //1 登录弹窗  2 显示头像 3领取加息券弹窗 4签到规则弹窗
    userInfo: app.globalData.userInfo,
    user_token: '',
    user_id: 0,
    username: '',
    sign_count: '', // sign_count 为签到总天数,
    receive_count: '', // receive_count 为领取加息券总张数
    sign_days: 0, //连续签到几天  也可以是加息券面值
    sign_datasum: 0, //今天是第几天
    is_receive: '', //是否已领取加息券
    is_sign: '', //是否已签到
    duigouSrc: '../../image/Sign-in.jpg', //对勾黄色
    huidianSrc: '../../image/gray.png', //灰色灰点
    huandianSrc: '../../image/yellow.png', //黄色黄点
    componsValue: 0,
    signBtnText: '签到',
    event: '',
    level_name: '普通会员',
    huiyuanSrc: '../../image/1putong.png',
    openstate: '', //签到活动是否开启
    alertTitle_top: '1',
    eventOneState: 0, //幸运抽奖活动是否开启
    eventTwoState:0, //砍价是否开启 0 开启 ,
    eventKanjiaState:0,//部署兑换小程序是否开启
  },
  onLoad: function() {

    var that = this;
    that.setData({
      componsValue: '-',
    });
  },
  moreActive: function() {
    var that = this;
    net.requestHttp('welfare/index/eventlist', {}, function(res) {
      /*
      {"state":1,"data":{"state":0,"data":{"starttime":"1544371200","endtime":"1547308800","rule":""}}
state为1活动开启，为0活动关闭,starttime活动开始时间戳（秒），endtime 活动结束时间戳（秒）,rule 活动规则，text下线文案
      */
      if (res.data.state == 1) {
        if(res.data.data.event2 == ""){//抽奖
          that.setData({
            eventOneState: 1,
          });
        } else {
          that.setData({
            eventOneState: 0,
          });
        }

        if(res.data.data.event3 == ""){//砍价
          that.setData({
            eventTwoState:1,
          });
        }else{
          that.setData({
            eventTwoState: 0,
          });
        }
        if(res.data.data.event4==""){//步数兑换
          that.setData({
            eventKanjiaState:1,
          })
        }else{
          that.setData({
            eventTwoState: 0,
          });
        }

      }
    });
  },
  //全局事件
  eventAction: function() {
    var that = this;
    net.requestHttp('welfare/index/event', {}, function(res) {
      /*
      {"state":1,"data":{"state":0,"data":{"starttime":"1544371200","endtime":"1547308800","rule":""}}
state为1活动开启，为0活动关闭,starttime活动开始时间戳（秒），endtime 活动结束时间戳（秒）,rule 活动规则，text下线文案
      */
      var article = res.data.data.rule;
      WxParse.wxParse('article', 'html', article, that, 5);
      if (res.data.state == 1) {
     
        that.setData({
          event: res.data.data,
          openstate: 1,
        });
      } else {
     
        that.setData({
          event: res.data.data,
          openstate: 0,
        });
      }
    });
  },
  // 发送fromID
  sendFormId: function (e) {
 
    if (e.detail.formId == undefined || e.detail.formId =='the formId is a mock one') {
      console.log('====' + e.detail);
    } else {
      var openid = wx.getStorageSync("openid")
      if (app.globalData.openid.length > 0 && e.detail.formId) {
        net.requestHttp('welfare/index/addformid', { form_id: e.detail.formId, user_id: app.globalData.userInfo.user_id, openid: openid })
      }
    }
  },
  getopenid:function(){
  
  var that = this;
    wx.login({
      success(res) {
        if (res.code) {
          var code = res.code;
          net.requestHttp('welfare/index/getopenid', {
            code: code
          }, function(res) {
            if (res.data.state == 1) {
              wx.setStorage({
                  key: "openid",
                  data: res.data.data.openid
                }),
                wx.getUserInfo({
                  success: function(ress) {
                    console.log(ress);
                    // gio('setVisitor', ress.userInfo);
                    that.setData({
                      nickName: ress.userInfo.nickName,
                      avatarUrl: ress.userInfo.avatarUrl,
                    });
                  }
                });
              app.globalData.openid = res.data.data.openid;
              app.globalData.session_key = res.data.data.session_key;

              that.loginAction(e);
            } else {
              //登录失败
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  //================================每次显示
  onShow: function() {
    var that = this;

    //全局事件
    that.eventAction();
    //更多活动
    that.moreActive();

    //每次都去获取openid 和以前登录的时候留存的userinfo 
    app.globalData.userInfo = wx.getStorageSync('userInfo');
    app.globalData.openid = wx.getStorageSync('openid');
    var alertTitle_top = wx.getStorageSync("alertTitle_top");
    

    //已经授权
    wx.getUserInfo({
      success: function(res) {
        that.setData({
          nickName: res.userInfo.nickName,
          avatarUrl: res.userInfo.avatarUrl,
        });
        //存在登录信息
        if (app.globalData.userInfo) {
          that.setData({
            showType: 0,
            nickName: res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl,
            userInfo: app.globalData.userInfo,
            username: app.globalData.userInfo.username,
            user_id: app.globalData.userInfo.user_id,
            user_token: app.globalData.userInfo.user_token,
          });

          if (alertTitle_top == 0) {
            that.setData({
              alertTitle_top: 0,
            });
          }

          that.getUserInfo();
        } else {
          that.setData({
            showType: 1, //1 登录弹窗  2 显示头像 3领取加息券弹窗 4签到规则弹窗
            alertTitle_top: 1,
          });
        }
      },
      fail: function(res) {
        that.setData({
          showType: 1, //1 登录弹窗  2 显示头像 3领取加息券弹窗 4签到规则弹窗
        });
      },
    });
  },
  onReady: function() {
    var that = this;
    //获得dialog组件
    that.dialog = that.selectComponent("#dialog");
  },
  showDialog() {
    // if(app.globalData.open_id.length != 10){
    var that = this;
    that.dialog.showDialog();
    // }
  },
  //取消事件
  _cancelEvent() {
    var that = this;
    console.log('你点击了取消');
    that.dialog.hideDialog();
  },
  //确认事件
  _confirmEvent(res) {
    var that = this;
    console.log(res.code + '你点击了确定');
    that.dialog.hideDialog();
  },
  //点击去登陆按钮
  _logoEvent() {
    //channel 小程序渠道 0 为签到，1是抽奖，2 砍价
    wx.navigateTo({
      url: '../logs/logs?channel=0',
    })
  },
  //点击暂不
  _notNowEvent(res) {
    var that = this;
    that.setData({
      showType: 0,
    });

    if (res._relatedInfo.anchorTargetText == '暂不'){
      wx.clearStorage();
      app.globalData.userInfo = null;
    }
  },
  //-======================================点击签到=============
  resignAction: function() {
    var that = this;
    if (that.data.is_sign == 0) {
      if (app.globalData.userInfo) {
        net.requestHttp("welfare/index/sign", {
          user_id: that.data.user_id,
          user_token: that.data.user_token
        }, function(res) {
          if (res.data.state == 1) {
            that.getUserInfo();
            wx.showToast({
              title: '签到成功',
            })
          }
        });
      } else {
        // that.setData({
        //   showType: 1,
        // });
        that.loginPage();
      }
    }
  },
  // =================================== 获取用户信息=========
  getUserInfo: function() {
    var that = this;
    //获取用户信息接口
    net.requestHttp("welfare/index/getUserInfo", {
      user_id: that.data.user_id,
      user_token: that.data.user_token
    }, function(res) {
      if (res.data.state == 1) {
        /*
          {"data":{"user_id":"657902","openid":"111","logintime":"1547605521","addtime":"1547540564","is_new":"0","nickname":"","headimgurl":"","username":"m-15021794401","sign_count":"3","receive_count":"0","level_name":"普通会员","is_sign":0,"is_receive":0,"sign_days":0},"msg":"","state":"1"}
        Sign_count 为签到总天数,
        receive_count 为领取加息券总张数，
        is_sign今天是否签到，
        is_receive”:今天是否领取’，
        sign_days当前连续签到天数
        */
        console.log(res.data.data);
        var signdataSUm = 0;
        if (res.data.data.is_sign == 1) { //界面需要显示当前是第几天;
          signdataSUm = res.data.data.sign_days - 1;
        } else {
          signdataSUm = res.data.data.sign_days;
        }
        that.setData({
          is_sign: res.data.data.is_sign,
          receive_count: res.data.data.receive_count,
          sign_count: res.data.data.sign_count,
          sign_days: res.data.data.sign_days,
          sign_datasum: signdataSUm,
          componsValue: res.data.data.sign_days,
          is_receive: res.data.data.is_receive,
          level_name: res.data.data.level_name
        });
        var leavename = res.data.data.level_name
        var src = '../../image/1putong.png';
        if (leavename == '普通会员') {
          src = '../../image/1putong.png';
        } else if (leavename == '银牌会员') {
          src = '../../image/2yin.png';
        } else if (leavename == '铜牌会员') {
          src = '../../image/3tong.png';
        } else if (leavename == '金牌会员') {
          src = '../../image/4jin.png';
        } else if (leavename == '钻石会员') {
          src = '../../image/5zuanshi.png';
        } else if (leavename == '白金会员') {
          src = '../../image/6baijin.png';
        }
        that.setData({
          huiyuanSrc: src,
        });


      } else {
        setTimeout(function(e) {
          that.getUserInfo();
        }, 3000);
      }
    });
  },
  // ============================登录======================
  loginAction: function() {
    var that = this;
    app.globalData.userInfo = wx.getStorageSync('userInfo');
    if (app.globalData.userInfo) {
      // that.dialog.showDialog();
      that.setData({
        showType: 2, //显示头像弹窗
      });
    } else {
      // that.setData({
      //   showType: 1,
      // });
      that.loginPage();
    }
  },
  //========================签到记录
  recordListAction: function(res) {
    var that = this;
    if (app.globalData.userInfo) {
      wx.navigateTo({
        url: '../RecordList/RecordList?state=0',
      })
    } else {
      // that.setData({
      //   showType:1,
      // });
      that.loginPage();
    }
  },
  //=====================  点击领取加息券按钮
  getComponsAction: function(res) {
    console.log('点击领取加息券按钮');
    var that = this;
    if (app.globalData.userInfo) {
      if (that.data.is_sign == 0) {
        wx.showToast({
          title: '请先签到',
          icon: 'none',
        });
        return;
      }

      if (that.data.is_receive == 0) {
        that.setData({
          showType: 3,
        });
      }
    } else {
      // that.setData({
      //   showType: 1,
      // });
      that.loginPage();
    }
  },
  //================= 领取加息券
  _getComponetsAction: function(res) {
    var that = this;
    if (app.globalData.userInfo) {
      net.requestHttp("welfare/index/receive", {
        user_id: that.data.user_id,
        user_token: that.data.user_token
      }, function(res) {
        if (res.data.state == 1) {
          that.getUserInfo();
          wx.showToast({
            title: '领取成功',
            duration: 1000,
          })

          setTimeout(function(e) {
            wx.navigateTo({
              url: '../RecordList/RecordList?state=1',
            })
          }, 1000);
        }
        that.setData({
          showType: 0,
        });
      });
    } else {
      that.setData({
        showType: 0,
      });
    }
  },
  //=========== 签到规则
  _resignrule: function() {
    var that = this;
    console.log('asfasfds');
    that.setData({
      showType: 4,
    });
  },
  //
  mygiftAction: function() {
    var that = this;
    if (app.globalData.userInfo) {
      // state=1 跳转礼物界面
      wx.navigateTo({
        url: '../RecordList/RecordList?state=1',
      })
    } else {
      // that.setData({
      //   showType: 1,
      // });
      that.loginPage();
    }
  },
  dismissalert_top: function() {
    var that = this;
    that.setData({
      alertTitle_top: 0,
    });
    wx.setStorage({
      key: 'alertTitle_top',
      data: 0,
    });

  },
  onShareAppMessage: function(e) {
    if (e.from === 'button') {
      return {
        title: '连续签到领7%加息券',
        imageUrl: '../../image/banner.jpg',
        path: 'pages/index/index?'
      }
    } else {
      return {
        title: '连续签到领7%加息券',
        imageUrl: '../../image/banner.jpg',
        path: 'pages/index/index?'
      }
    }
  },
  loginPage: function() {
    wx.navigateTo({
      url: '../logs/logs?channel=0',
    })
  },
  luckydraw: function() {

    var that = this;
    if (that.data.eventOneState == 0) {

      wx.navigateTo({
        url: '../lottery/lottery',
      })
    } 

    /*
    else {
    
      if (app.globalData.userInfo) {
        console('以后添加其他操作');
      } else {
        that.loginPage();
      }
    }
    */
  },
  bargain:function(){
    var that  = this;
    if(that.data.eventTwoState == 0){
      wx.navigateTo({
        url: '../Bargain/Bargain?channel=2',
      })
    }
  }
})